package cn.xuewenbao.edu.service.impl;

import cn.xuewenbao.edu.entity.LearnRecord;
import cn.xuewenbao.edu.entity.WeekLearnTime;
import cn.xuewenbao.edu.entity.vo.MyLearnRecordVo;
import cn.xuewenbao.edu.entity.vo.MyLikeOrFavoriteContentVo;
import cn.xuewenbao.edu.mapper.LearnRecordMapper;
import cn.xuewenbao.edu.service.ColumnTypeService;
import cn.xuewenbao.edu.service.CourseService;
import cn.xuewenbao.edu.service.LearnRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class LearnRecordServiceImpl extends ServiceImpl<LearnRecordMapper, LearnRecord> implements LearnRecordService {

    private static final String COURSE_TYPE = "2";
    private static final String BOOK_TYPE = "4";

    @Autowired
    private ColumnTypeService columnTypeService;
    @Autowired
    private CourseService courseService;

    @Override
    public Result<?> updateLearnRecord(LearnRecord learnRecord) {
        //参数检查
        if (learnRecord == null) {
            return Result.error("新的学习记录信息为空");
        }
        String columnType = learnRecord.getColumnType();
        String contentId = learnRecord.getContentId();
        if (StringUtils.isEmpty(columnType) || !StringUtils.isNumeric(columnType) || StringUtils.isEmpty(contentId)) {
            return Result.error("学习记录的内容信息不正确");
        }

        //查询是否已有记录
        QueryWrapper<LearnRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("content_id", contentId).eq("column_type", columnType).eq("user_id", learnRecord.getUserId());
        //如果是课程和讲书, 需增加新的content_subject来确定学习记录
        if (COURSE_TYPE.equals(columnType) || BOOK_TYPE.equals(columnType)) {
            queryWrapper.eq("content_subject", learnRecord.getContentSubject());
        }
        LearnRecord queryRecord = baseMapper.selectOne(queryWrapper);

        //没有学习记录, 添加
        if (queryRecord == null) {
            int insert = baseMapper.insert(learnRecord);
            if (insert < 1) {
                return Result.error("新的学习记录添加失败");
            }
            return Result.OK("新的学习记录添加成功");
        }

        //已有学习记录, 更新
        UpdateWrapper<LearnRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("content_id", contentId).eq("column_type", columnType).eq("user_id", learnRecord.getUserId());
        //针对课程和讲书, 增加content_subject来确定学习记录, 并更新current_time
        if (COURSE_TYPE.equals(columnType) || BOOK_TYPE.equals(columnType)) {
            updateWrapper.eq("content_subject", learnRecord.getContentSubject());
            //更新当前播放进度(可能用户会回放到已学过的内容, 此时当前进度 < 已学习进度)
            updateWrapper.set("`current_time`", learnRecord.getCurrentTime());  //current_time为 MYSQL关键字, 需加``
            //如果有更长的已学习进度, 更新已学习进度
            if (queryRecord.getLearnedTime() == null ||
                    learnRecord.getLearnedTime() > queryRecord.getLearnedTime()) {
                updateWrapper.set("learned_time", learnRecord.getLearnedTime());
            }
            //如果没有内容总时长, 更新总时长
            if (queryRecord.getTotalTime() == null || queryRecord.getTotalTime().equals(0.0)) {
                updateWrapper.set("total_time", learnRecord.getTotalTime());
            }
        }
        updateWrapper.set("gmt_modified", new Date());
        int update = baseMapper.update(null, updateWrapper);    //实体类传入null, 只更新 wrapper中 set()指定的字段
        if (update < 1) {
            return Result.error("学习记录更新失败");
        }
        return Result.OK("学习记录更新成功");
    }

    @Override
    public Double getCurrentTime(String userId, String contentId, String columnType, String contentSubject) {
        QueryWrapper<LearnRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("content_id", contentId)
                .eq("column_type", columnType).eq("content_subject", contentSubject);
        LearnRecord learnRecord = baseMapper.selectOne(wrapper);
        if (learnRecord != null) {
            return learnRecord.getCurrentTime();
        }
        return null;
    }

    @Override
    public Map<String, Double> getCurrentTimeAndTotalTime(String userId, String contentId, String columnType, String contentSubject) {
        QueryWrapper<LearnRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("content_id", contentId)
                .eq("column_type", columnType).eq("content_subject", contentSubject);
        LearnRecord learnRecord = baseMapper.selectOne(wrapper);
        if (learnRecord == null) {
            return null;
        }
        Map<String, Double> result = new HashMap<>();
        if (learnRecord.getCurrentTime() != null) {
            result.put("currentTime", learnRecord.getCurrentTime());
        }
        if (learnRecord.getTotalTime() != null) {
            result.put("totalTime", learnRecord.getTotalTime());
        }
        return result;
    }

    @Override
    public Result<?> getLearnRecord(String userId, String columnType) {
        List<MyLearnRecordVo> voList = new ArrayList<>();

        QueryWrapper<LearnRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("column_type", columnType).orderByDesc("gmt_modified");
        List<LearnRecord> learnRecordList = baseMapper.selectList(queryWrapper);

        for (LearnRecord learnRecord : learnRecordList) {
            MyLearnRecordVo vo = new MyLearnRecordVo();
            BeanUtils.copyProperties(learnRecord, vo);
            //获取对应专栏的内容信息
            String tableName = columnTypeService.getColumnTypeById(columnType);
            if (tableName == null) {
                return Result.error("收藏内容的类型columnType不正确");
            }
            MyLikeOrFavoriteContentVo contentVo = columnTypeService.selectMyLikeOrFavoriteContent(learnRecord.getContentId(), tableName);
            if (contentVo == null) {
                continue;
            }
            BeanUtils.copyProperties(contentVo, vo);
            if (COURSE_TYPE.equals(columnType) && !StringUtils.isBlank(learnRecord.getContentSubject())) {
                String chapterName = courseService.getCourseChapterName(learnRecord.getContentSubject());
                if (chapterName != null) {
                    vo.setContentSubjectName(chapterName);
                }
            }
            voList.add(vo);
        }
        return Result.OK(voList);
    }
}
